package com.android.svmc.app.mobile.activity;

import java.io.File;
import java.util.ArrayList;

import luyenlv.pro.screen.base.BaseActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.svmc.app.mobile.adapter.ListPictureAdapter;
import com.android.svmc.app.mobile.controller.SDCardController;
import com.android.svmc.app.mobile.controller.WifiManagement;
import com.android.svmc.app.mobile.data.JsonData;
import com.android.svmc.app.mobile.model.PictureModel;
import com.android.svmc.app.mobile.tabmanager.TabGroupActivity;
import com.android.svmc.app.mobile.util.CommonDefine;
import com.android.svmc.app.mobile.util.SettingUtils;
import com.android.svmc.app.mobile.view.FontTextView;

public class PictureMainActivity extends BaseActivity implements OnClickListener,CommonDefine{
	private ListView ls_allpicture;
	private Button btn_next;
	private Button btn_previous;
	private Button btn_reload;
	private TextView txt_page;
	private TextView emtry_data;
	private ListPictureAdapter myadapter;
	private ArrayList<PictureModel> list = new ArrayList<PictureModel>();
	private TabGroupActivity parentActivity;
	private RelativeLayout rl_loading;
	private loadpicture load_asynctask;
	
	private static int MAX_PAGE = 0;
	private static int page = 1;
	private static boolean istheFirst = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(getLayout(R.array.list_all_picture_layout));
		unitUI();
		parentActivity =(TabGroupActivity)getParent();
		setclicklistener();
	//	new loadpicture().execute();
		if(WifiManagement.haveNetworkConnection()==true){
			emtry_data.setVisibility(View.GONE);
			load_asynctask = new loadpicture();
			load_asynctask.execute();
		}else if (SettingUtils.getbooleanPreferences(this, IS_OFFLINE_MODE)==true) {
			SDCardController sdcard = new SDCardController(this);
			JsonData json = new JsonData();
			File filedata = new File(getExternalCacheDir()+APP_FOLDER, FILE_DATA_OFFLINE_PICTURE);
			if(filedata.exists()){
				String data = sdcard.ReadFromSdCard(APP_FOLDER +"/"+FILE_DATA_OFFLINE_PICTURE, "");
				list = json.getAllPictureOffline(data);
				if (list.size() > 0){
					myadapter = new ListPictureAdapter(PictureMainActivity.this, list, WifiManagement.haveNetworkConnection());
					ls_allpicture.setAdapter(myadapter);
					myadapter.notifyDataSetChanged();
				}else {
					emtry_data.setVisibility(View.VISIBLE);
				}		
			}else {
				emtry_data.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	public void clearMemory() {
		unbindReferences(this, R.id.list_all_picture_rl_root);
	}
	private void unitUI(){
		TextView title = (TextView)findViewById(R.id.list_all_picture_titlebar_txt_title);
		FontTextView.setfontHelveticaBold(title, this);
		title.setText(R.string.tab_pictures);
		ls_allpicture =(ListView)findViewById(R.id.list_all_picture_listview);
		ls_allpicture.setDivider(null);
		ls_allpicture.setDividerHeight(0);
		btn_reload = (Button)findViewById(R.id.list_all_picture_btn_reload);
		emtry_data = (TextView)findViewById(R.id.list_all_picture_txt_emtry);
		emtry_data.setVisibility(View.GONE);
		/***********************************
		 *  Add Footer ListView
		 **********************************/
		View footerView = getLayoutInflater().inflate(R.layout.footer_list_picture, ls_allpicture, false);
		btn_next = (Button)footerView.findViewById(R.id.navbar_btn_next);
		btn_previous =(Button)footerView.findViewById(R.id.navbar_btn_previous);
		txt_page =(TextView)footerView.findViewById(R.id.navbar_txt_number_pages);
		FontTextView.setfontMuseo900_regular(txt_page, this);
		txt_page.setText("Trang : "+page);
		ls_allpicture.addFooterView(footerView);
		/***********************************/
		/***********************************
		 *  add header
		 ***********************************/
		rl_loading = (RelativeLayout)findViewById(R.id.list_all_picture_rl_loading);
		TextView txt_loading = (TextView)findViewById(R.id.header_listview_listpic_txt_loading);
		FontTextView.setfontMyriadPro_semiBold(txt_loading, this);
		rl_loading.setVisibility(View.GONE);
	}
	private void setclicklistener(){
		btn_next.setOnClickListener(this);
		btn_previous.setOnClickListener(this);
		btn_reload.setOnClickListener(this);
		listenClickListView(ls_allpicture);
		
		
	}
	private void listenClickListView(ListView listview) {
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long id) {
				if(WifiManagement.haveNetworkConnection()==true){
					Intent out  = new Intent(PictureMainActivity.this, DetailPostActivity.class);
					out.putExtra(ID_ACTIVITY, PICTURE_ACTIVITY);
					out.putExtra(ID_POST, list.get(position).getId());
					out.putExtra(TITLE, list.get(position).getTitle());
					parentActivity.startChildActivity("DetailPostActivity", out);
				}else {
					Toast.makeText(PictureMainActivity.this, "Chế độ offline không hỗ trợ xem ảnh", 0).show();
				}
				
			}
		});
		
	}
	private class loadpicture extends AsyncTask<Void, Void, Void>{		
	//	ProgressDialog dialog;
		@Override
		protected Void doInBackground(Void... params) {
			JsonData json = new JsonData(PictureMainActivity.this);
			list = json.getAllPicture(DEFAULT_ID, page);
			//list_pre = json.getAllPicture(DEFAULT_ID, page -1);
			if (istheFirst == true){
				MAX_PAGE = json.getMaxPage();
				int totalPic = json.getTotalPictures();
				istheFirst = false;
				/**********************************************************************/
				SDCardController sdcard = new SDCardController(PictureMainActivity.this);
				sdcard.creatNewFolder(APP_FOLDER);
				sdcard.writeOneLineToSdcard(""+totalPic, APP_FOLDER+"/"+FILE_CONSTANT_TOTAL_PIC);
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			rl_loading.setVisibility(View.GONE);
			ls_allpicture.setPadding(0, 0, 0, 0);
			Log.i("anhson", "max pages " +MAX_PAGE);
//			dialog.dismiss();
			if (list.size() > 0){
				myadapter = new ListPictureAdapter(PictureMainActivity.this, list, WifiManagement.haveNetworkConnection());
				ls_allpicture.setAdapter(myadapter);
				myadapter.notifyDataSetChanged();
			}		
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			rl_loading.setVisibility(View.VISIBLE);
			ls_allpicture.setPadding(0, 30, 0, 0);
			btn_next.setVisibility(View.VISIBLE);
			btn_previous.setVisibility(View.VISIBLE);
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(load_asynctask !=null && !load_asynctask.isCancelled()){
			load_asynctask.cancel(true);
		}
		ls_allpicture = null;
		btn_next = null;
		btn_previous =null;
		txt_page =null;
		rl_loading =null;
		System.gc();		
	}

	/**
	 * Get context in groupActivity.Use for show dialog
	 * 
	 * @return : context
	 */
	private Context getDialogContext() {
		Context mcontext;
		if (getParent() != null)
			mcontext = getParent();
		else
			mcontext = this;
		return mcontext;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.navbar_btn_next:
			if(WifiManagement.haveNetworkConnection()){
				emtry_data.setVisibility(View.GONE);
				page = page+1;
				if (page <= MAX_PAGE ){
					new loadpicture().execute();
					load_asynctask = new loadpicture();
					load_asynctask.execute();
					txt_page.setText("Trang : "+page);

				}else {
					btn_next.setVisibility(View.INVISIBLE);
					Toast.makeText(PictureMainActivity.this,this.getString(R.string.info_server_full), 0).show();
					page = MAX_PAGE;
				}
			}else {
				Toast.makeText(this,this.getString(R.string.label_dialog_info_network), Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.navbar_btn_previous:
			if(WifiManagement.haveNetworkConnection()){
				emtry_data.setVisibility(View.GONE);
				page = page - 1;
				if ( page > 0){
					//new loadpicture().execute();
					load_asynctask = new loadpicture();
					load_asynctask.execute();
					txt_page.setText("Trang : "+page);
				}else {
					btn_previous.setVisibility(View.INVISIBLE);
					Toast.makeText(PictureMainActivity.this, "Số trang phải lớn hơn 1 ", 0).show();
					page = 1;
				}
			}else {
				Toast.makeText(this, this.getString(R.string.label_dialog_info_network), Toast.LENGTH_LONG).show();
			}		
			break;
		case R.id.list_all_picture_btn_reload:
			if(WifiManagement.haveNetworkConnection()==true){
				emtry_data.setVisibility(View.GONE);
				load_asynctask = new loadpicture();
				load_asynctask.execute();
			}else {
				Toast.makeText(this, getString(R.string.label_dialog_info_network), 0).show();
			}
			
			break;
		default:
			break;
		}
		
	}

}
